package com.bub.pay.api.service.impl;

import com.bub.pay.api.service.SystemManagementService;
import com.bub.pay.core.dao.SysLogDao;
import com.bub.pay.core.dao.SysUserDao;
import com.bub.pay.core.dao.UserLoginWhiteDao;
import com.bub.pay.core.entity.domain.SysLog;
import com.bub.pay.core.entity.domain.SysUser;
import com.bub.pay.core.entity.domain.UserLoginWhite;
import com.bub.pay.core.entity.dto.merchant.SysLogDTO;
import com.bub.pay.core.entity.dto.merchant.UserAccountDTO;
import com.bub.pay.core.entity.vo.merchant.QueryIpWhiteVO;
import com.bub.pay.core.entity.vo.merchant.ResetEmailVo;
import com.bub.pay.core.entity.vo.merchant.ResetNickNameVo;
import com.bub.pay.core.enums.DeleteFlagEnum;
import com.bub.pay.core.manager.email.EmailService;
import com.bub.pay.core.manager.user.UserCommonManager;
import com.bub.pay.framework.common.base.Cause;
import com.bub.pay.framework.common.base.Module;
import com.bub.pay.framework.common.entity.model.SessionModel;
import com.bub.pay.framework.common.exception.GlobalException;
import com.bub.pay.framework.common.util.ContextHolder;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商户系统设置管理 服务类
 */
@Service
public class SystemManagementServiceImpl implements SystemManagementService {

    @Resource
    private UserLoginWhiteDao userLoginWhiteDao;

    @Resource
    private SysLogDao sysLogDao;

//    @Resource
//    private AccountDao accountDao;
//
//    @Resource
//    private MerchantDao merchantDao;

    @Resource
    private SysUserDao sysUserDao;

    @Autowired
    private UserCommonManager userCommonManager;
    @Autowired
    private EmailService emailService;

    @Override
    public UserAccountDTO selectUserAccount() {
        //获取当前登录用户
        SessionModel sessionModel = ContextHolder.currentUserInfo();

        Long userId = sessionModel.getUserId();
        String email = sessionModel.getEmail();
        String userName = sessionModel.getLoginName();
        String nickName = sessionModel.getNickName();
        String roleName = sessionModel.getRoleName();
        Long extendId = sessionModel.getExtendId();

        //查询账户信息
//        Account account = new Account();
//        account.setExtendId(extendId);
//        account  = accountDao.selectOne(account);
//
//        Merchant merchant = new Merchant();
//        merchant.setId(extendId);
//        merchant = merchantDao.selectOne(merchant);
//
        UserAccountDTO dto = new UserAccountDTO();
//        dto.setUserId(userId);
//        dto.setTotalAmount(account.getTotalAmount());
//        dto.setUserName(userName);
//        dto.setNickName(nickName);
//        dto.setRoleName(roleName);
//        dto.setAgentId(merchant.getAgentId());
//        dto.setEmail(email);
//        dto.setWalletAddress(StrUtil.hideCenterNumber(account.getAccAddr(),2,4));
//        dto.setPayRate(merchant.getPayRate());
        return dto;
    }

    @Override
    public boolean resetNickName(ResetNickNameVo vo) throws Exception {
        //获取当前登录用户
        SessionModel sessionModel = ContextHolder.currentUserInfo();

        SysUser user = new SysUser();
        user.setId(sessionModel.getUserId());
        user.setNickName(vo.getNickName());

        int count = sysUserDao.updateByPrimaryKeySelective(user);

        if (count < 1){
            throw new GlobalException(Module.merchant,Cause.operat_fail);
        }

        //数据更新 , 可以考虑使用多线程
        UserLoginWhite white = new UserLoginWhite();
        white.setCreateId(sessionModel.getUserId());
        white.setCreateName(vo.getNickName());
        userLoginWhiteDao.updateByPrimaryKeySelective(white);

        userCommonManager.refreshSession(sessionModel.getUserId().toString());

        return true;
    }

    @Override
    @Transactional
    public boolean changeEmail(ResetEmailVo vo) throws Exception {
        //获取当前登录用户
        SessionModel sessionModel = ContextHolder.currentUserInfo();
        SysUser user = new SysUser();
        user.setId(sessionModel.getUserId());
        user.setEmail(vo.getEmail());
        int count = sysUserDao.updateByPrimaryKeySelective(user);
        if (count < 1){
            throw new GlobalException(Module.merchant,Cause.operat_fail);
        }
        emailService.checkEmailCode(vo.getEmail(),vo.getEmailCode());
        userCommonManager.refreshSession(sessionModel.getUserId().toString());
        return true;
    }

    @Override
    public Map<String,String> selectAccAddr() {
        //获取当前登录用户
        SessionModel sessionModel = ContextHolder.currentUserInfo();
        //查询账户信息
//        Account account = new Account();
//        account.setExtendId(sessionModel.getExtendId());
//        account  = accountDao.selectOne(account);
        Map<String,String> map = new HashMap<>();
//        map.put("walletAddress",account.getAccAddr());
        return map;

    }


    @Override
    public PageInfo<SysLogDTO> querySysLog(QueryIpWhiteVO vo) {
        //获取当前登录用户
        SessionModel sessionModel = ContextHolder.currentUserInfo();

        //创建查询条件
        Example example = new Example(SysLog.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("extendId",sessionModel.getExtendId())
                .andEqualTo("userType",sessionModel.getUserType())
                .andEqualTo("delFlag", DeleteFlagEnum.using.flag);

        if (null != vo.getCreateId()){
            criteria.andLike("createId","%"+vo.getCreateId()+"%");
        }
        if (StringUtils.isNotBlank(vo.getCreateName())){
            criteria.andLike("createName","%"+vo.getCreateName()+"%");
        }
        if (null != vo.getStartTime()){
            criteria.andGreaterThanOrEqualTo("createDate",vo.getStartTime());
        }
        if (null != vo.getEndTime()){
            criteria.andLessThanOrEqualTo("createDate",vo.getEndTime());
        }

        example.orderBy("createDate").desc();

        //分页查询数据
        PageHelper.startPage(vo.getPageNo(),vo.getPageSize());
        List<SysLog> list = sysLogDao.selectByExample(example);
        List<SysLogDTO> dtoList = new ArrayList<>();
        long total = 0;
        if (list instanceof Page) {
            total = ((Page) list).getTotal();
        }

        if (CollectionUtils.isNotEmpty(list)){
            dtoList = list.stream().map(m -> {
                SysLogDTO dto = new SysLogDTO();
                BeanUtils.copyProperties(m,dto);
                return dto;
            }).collect(Collectors.toList());
        }
        PageInfo pageInfo = new PageInfo<>(dtoList);
        pageInfo.setTotal(total);
        return pageInfo;
    }
}
